package com.itheima.servlet;

import com.itheima.baen.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/listStudentServlet")
public class listStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 创建字符输入流对象，关联要读取的文件
        BufferedReader br = new BufferedReader(new FileReader("d:\\stu.txt"));

        // 创建集合，用于保存对象
        ArrayList<Student> list = new ArrayList<>();

        // 循环读取，封装数据
        String line;
        while ((line = br.readLine())!=null){
            String[] arr = line.split(",");
            Student stu = new Student();
            stu.setName(arr[0]);
            stu.setAge(Integer.parseInt(arr[1]));
            stu.setScore(Integer.parseInt(arr[2]));
            list.add(stu);
        }

        /*// 将数据响应给浏览器
        resp.setContentType("text/html;charset=UTF-8");
        // 获取输出流对象
        for (Student s : list) {
            resp.getWriter().write(s.getName()+","+s.getAge()+","+s.getScore()+"<br>");
        }*/
        // 将集合对象存入会话域
        req.getSession().setAttribute("student",list);
        // 重定向到listStudent.jsp页面
        resp.sendRedirect("/listStudent.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
